/**********************************************************
 * File description:samplelibrary.cpp
 * Function: 样本库ui逻辑
 * Current Version: 1.0.0
 * Author: 张宇轩
 * Date: 2022-10-05
 *  -----
 *  Copyright by bokun Software.
 **********************************************************/
#include "samplelibraryui.h"
#include "ui_samplelibraryui.h"

#include <QMessageBox>
#include <QColorDialog>
#include <QDebug>

SampleWidget::SampleWidget(QDialog *parent) :
    QDialog(parent),
    ui(new Ui::SampleWidget)
{
    ui->setupUi(this);
    this->setWindowFlags(Qt::CustomizeWindowHint|Qt::WindowCloseButtonHint);

    addNSam = new AddNewSample();
    SLDB = new SampleLibrary();
    cusMsg = new CustomMessageBox();

    ui->sampleTable->hideColumn(6);
    ui->sampleTable->hideColumn(7);

    /* 自适应宽度 */
    ui->sampleTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    /* 调整色块列宽度以同步色块宽度 */
    ui->sampleTable->horizontalHeader()->setSectionResizeMode(0, QHeaderView::Interactive);
    ui->sampleTable->setColumnWidth(0, 40);

    /* 靶基因列表备注校验 */
    QRegExp sampleCommentrx(".{1,30}");
    ui->sampleTable->setItemDelegateForColumn(4, new CustomItemDelegrate(sampleCommentrx));
    /* 样本名称 */
    QRegExp sampleNamerx("(\\w|-){1,40}");
    ui->sampleTable->setItemDelegateForColumn(1, new CustomItemDelegrate(sampleNamerx));

    /* 获取并渲染默认样本 */
    this->getDefaultSample();

    connect(ui->newSample, &QPushButton::clicked, this, [=](){
        addNSam->exec();
    });
    connect(addNSam, &AddNewSample::newSampleInfo, this, &SampleWidget::operateSampleLibToDB);
    connect(ui->filter, &QPushButton::clicked, this, &SampleWidget::filterSampleTable);
    connect(ui->reset, &QPushButton::clicked, this, [=](){
        for(int i = 0; i < ui->sampleTable->rowCount(); i++) ui->sampleTable->showRow(i);
        ui->filterItem->clear();
    });
    connect(ui->sampleTable, &QTableWidget::cellChanged, this, &SampleWidget::reviseSampleTable);
    connect(ui->ok, &QPushButton::clicked, this, [=]{
        emit SampleWidget::okExport();
        this->close();
    });

    // 调用show方法
    QList<QHash<QString,QString>> allSampleInfos = SLDB->show();
    /* 渲染 */
    this->renderSampleInfo(allSampleInfos);
}

SampleWidget::~SampleWidget()
{
    delete ui;
}


void SampleWidget::getDefaultSample(){
    QString path = QCoreApplication::applicationDirPath();
    char * filePath;
    QByteArray tempByte = (path + "/" + CONFIG_FILE_NAME).toLocal8Bit();
    filePath = tempByte.data();
    Simplexml * simplexml = new Simplexml(filePath);
    simplexml->next("reaction-plate");

    QList<Sample> defaultSamples;
    QList<QHash<QString, QString>> defaultHashList;
    QHash<QString, QString> defaultHash;

    for(int i = 0;i < 3;i ++){
        Sample sample;
        sample.name = QString::fromStdString(simplexml->child("default-samples")->child("sample",i)->child("name")->text());
        defaultSamples.append(sample);
    }

    /* 将 QList<Sample> 改为 QList<QHash<QString, QString>> 后渲染 */
    for(int i = 0; i < defaultSamples.size(); i++){
        QString rgbNums = QString::number(rgbNum[i][0]) + "," + QString::number(rgbNum[i][1]) + "," + QString::number(rgbNum[i][2]);
        QString rgb = "rgb(" + rgbNums + ");";
        defaultHash.insert("color_value", rgb);
        defaultHash.insert("name", defaultSamples[i].name);
        defaultHash.insert("create_time", defaultSamples[i].create_time);
        defaultHash.insert("update_time", defaultSamples[i].update_time);
        defaultHash.insert("remarks",defaultSamples[i].remarks);
        defaultHash.insert("id", defaultSamples[i].id);
        defaultHashList.append(defaultHash);
    }

    /* 渲染默认样本 */
    this->renderSampleInfo(defaultHashList);


}

/*!
 * \brief 渲染新建样本槽函数
 *
 * \param QString sampleName, Qstring sampleColoe
 * \param QString comment
 *
 * \return void
 *
 * Detail here!!!
 */
void SampleWidget::renderSampleInfo(QList<QHash<QString,QString>> allSampleInfos){
    ui->sampleTable->blockSignals(true);    // 阻塞信号
    for(int i = 0; i < allSampleInfos.size(); i++){
        /* 色块居中组件 */
        QWidget *colorWidget = new QWidget();
        /* 色块居中布局 */
        QHBoxLayout *colorVLayout = new QHBoxLayout(colorWidget);

        QHash<QString,QString> rows = allSampleInfos[i];

        QPushButton *colorBtn = new QPushButton();
        colorBtn->setCursor(Qt::PointingHandCursor);

        QPushButton *deleteSample = new QPushButton();
        //        deleteSample->setIcon(QIcon(":/icon/icon/delete_btn.svg"));
        //        deleteSample->setIconSize(QSize(35, 35));
        deleteSample->setStyleSheet("background: transparent; border: none; font-family: 'Alibaba PuHuiTi'");
        deleteSample->setText("删除");
        deleteSample->setCursor(Qt::PointingHandCursor);

        QString styleSheet = "background: " + rows["color_value"];
        styleSheet += "; border: 1px solid rgba(0,0,0,.16);";
        colorBtn->setMaximumWidth(40);
        colorBtn->setMaximumHeight(45);
        colorBtn->setStyleSheet(styleSheet);
        colorVLayout->addWidget(colorBtn);
        colorVLayout->setSpacing(0);
        colorVLayout->setMargin(0);

        int row = ui->sampleTable->rowCount();

        ui->sampleTable->setRowCount(row+1);
        ui->sampleTable->setCellWidget(row, 0, colorWidget);
        ui->sampleTable->setItem(row, 1, new QTableWidgetItem(rows["name"]));
        ui->sampleTable->setItem(row, 2, new QTableWidgetItem(rows["create_time"]));
        ui->sampleTable->setItem(row, 3, new QTableWidgetItem(rows["update_time"]));
        ui->sampleTable->setItem(row, 4, new QTableWidgetItem(rows["remarks"]));
        ui->sampleTable->setCellWidget(row, 5, deleteSample);
        ui->sampleTable->setItem(row, 6, new QTableWidgetItem(rows["id"]));
        ui->sampleTable->setItem(row, 7, new QTableWidgetItem(rows["color_value"]));

        ui->sampleTable->item(row, 2)->setFlags(ui->sampleTable->item(row,2)->flags() & ~Qt::ItemIsEditable);
        ui->sampleTable->item(row, 3)->setFlags(ui->sampleTable->item(row,3)->flags() & ~Qt::ItemIsEditable);


        connect(deleteSample, &QPushButton::clicked, this, [=](){
            QString queryText = "确认删除样本 \"" + rows["name"] + "\" ?";
            if(QMessageBox::Yes == cusMsg->show(this, CMsg::CQuestion, "确认删除", queryText)){
                SLDB->remove(rows["id"]);
                /* 初始化 */
                ui->sampleTable->setRowCount(0);
                /* 渲染默认样本 */
                this->getDefaultSample();
                // 调用show方法
                QList<QHash<QString,QString>> allSampleInfos = SLDB->show();
                this->renderSampleInfo(allSampleInfos);
            }

        });
        connect(colorBtn, &QPushButton::clicked, this, [=](){
            QColor c = QColorDialog::getColor(Qt::black, this);
            if(!c.isValid()) return;
            int r, g, b;
            QString styleSheet = "background: ";
            QString rgb = "rgb(";
            r = c.red();
            g = c.green();
            b = c.blue();
            rgb += QString::number(r);
            rgb += ",";
            rgb += QString::number(g);
            rgb += ",";
            rgb += QString::number(b);
            rgb += ");";
            styleSheet += rgb;
            styleSheet += "; border: none;";
            colorBtn->setStyleSheet(styleSheet);
            ui->sampleTable->setItem(row, 7, new QTableWidgetItem(rgb));
        });
    }
    ui->sampleTable->blockSignals(false);   // 恢复信号

}

/*!
 * \brief 过滤样板表信息
 *
 * \return void
 *
 * Detail here!!!
 */
void SampleWidget::filterSampleTable(){
    int filterKey = ui->filterKey->currentIndex();
    int filterCondition = ui->filterCondition->currentIndex();
    QString filterItem = ui->filterItem->displayText();
    int column;
    for(int i = 0; i < ui->sampleTable->rowCount(); i++) ui->sampleTable->showRow(i);
    if(filterItem == "")
        return;

    switch(filterKey){
    case 0: column = 1; break;
    }

    switch(filterCondition){
    case 0:
        for(int i = 0; i < ui->sampleTable->rowCount(); i++){
            if(filterItem != ui->sampleTable->item(i, column)->text()){
                ui->sampleTable->hideRow(i);
            }

        }; break;
    case 1:
        for(int i = 0; i < ui->sampleTable->rowCount(); i++){
            if(filterItem == ui->sampleTable->item(i, column)->text()){
                ui->sampleTable->hideRow(i);
            }

        }; break;
    }

}

/*!
 * \brief 将新样本信息传入数据库
 *
 * \return
 *
 * Detail here!!!
 */
void SampleWidget::operateSampleLibToDB(AddNewSample::SampleStruct newSampleInfo){
    // 插入
    SLDB->create(newSampleInfo.sampleName, newSampleInfo.colorValue, newSampleInfo.comment);
    addNSam->close();
    /* 排序 */
    //    for(int i = 0;i < allSampleInfos.size();i ++){
    //        for(int j = i + 1;j < allSampleInfos.size();j ++){
    //            int k = allSampleInfos[i]["id"].toInt();
    //            int l = allSampleInfos[j]["id"].toInt();
    //            if(k > l){
    //                QHash<QString,QString> t = allSampleInfos[i];
    //                allSampleInfos[i] = allSampleInfos[j];
    //                allSampleInfos[j] = t;
    //            }
    //        }
    //    }
    /* 初始化 */
    ui->sampleTable->setRowCount(0);
    /* 渲染默认样本 */
    this->getDefaultSample();
    // 调用show方法
    QList<QHash<QString,QString>> allSampleInfos = SLDB->show();
    /* 渲染 */
    this->renderSampleInfo(allSampleInfos);
}

void SampleWidget::reviseSampleTable(int row, int column){
    SLDB->revise(
                ui->sampleTable->item(row, 6)->text(),
                ui->sampleTable->item(row, 1)->text(),
                ui->sampleTable->item(row, 7)->text(),
                ui->sampleTable->item(row, 4)->text()
                );
    /* 初始化 */
    ui->sampleTable->setRowCount(0);
    /* 渲染默认样本 */
    this->getDefaultSample();
    // 调用show方法
    QList<QHash<QString,QString>> allSampleInfos = SLDB->show();
    /* 渲染 */
    this->renderSampleInfo(allSampleInfos);
}

